package com.typhoon.rpc.common.codec;

import java.util.List;

import com.typhoon.rpc.common.util.SerializationUtil;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 解码
 * 
 * @author typhoon
 *
 */
public class RpcDecoder extends ByteToMessageDecoder {

	  /**
     * 目标类
     */
    private Class<?> genericClass;

    public RpcDecoder(Class<?> genericClass) {
        this.genericClass = genericClass;
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {//检查是否有可读取的数据
            return;
        }
        in.markReaderIndex();//标记读取开始
        int dataLength = in.readInt();//
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        out.add(SerializationUtil.deserialize(data, genericClass));
    }

}
